package chapter04.part02;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 可中断套接字 可用通过中断来接触阻塞
 * 
 * @author insight
 * @since 2021/8/29
 */
public class SocketChannelTest {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                SocketChannel channel =
                        SocketChannel.open(new InetSocketAddress(InetAddress.getLocalHost(), 8080));
                Scanner in = new Scanner(channel, StandardCharsets.UTF_8);
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("Reading...");
                    if (in.hasNextLine()) {
                        System.out.println(in.nextLine());
                    }
                }
                System.out.println("t1 finished...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                Socket socket = new Socket(InetAddress.getLocalHost(), 8080);
                Scanner in = new Scanner(socket.getInputStream(),
                        StandardCharsets.UTF_8);
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("Reading...");
                    if (in.hasNextLine()) {
                        System.out.println(in.nextLine());
                    }
                }
                System.out.println("t2 finished...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        
        t1.start();
        t2.start();

        Thread.sleep(3000);
        
        // Socket 无法被中断
        // SocketChannel 可以被中断
        new Thread(t1::interrupt).start();
        new Thread(t2::interrupt).start();
    }
}